package com.south.base.test.thread;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;

/**
 * @author Administrator
 * @date 2019/12/5 15:33
 */
@Slf4j
public class WaitNotify {
    @Test
    public void waitNotify() {
        CountDownLatch countDownLatch = new CountDownLatch(3);
        Object wait = WaitNotify.class;
        // wait
        new Thread(() -> {
            try {
                synchronized (wait) {
                    wait.wait();
                    log.info("wait1 end");

                    wait.wait();
                    log.info("wait2 end");
                }
            } catch (InterruptedException e) {
                log.error("", e);
            }
            countDownLatch.countDown();
        }).start();
        // notify wait
        new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                log.error("", e);
            }
            synchronized (wait) {
                // 判断当前线程是否持有wait对象锁
                if (Thread.holdsLock(wait)) {
                    log.info("当前线程持有wait对象锁");
                    wait.notify();
                    log.info("notify end");
                }
                try {
                    wait.wait();
                } catch (InterruptedException e) {
                    log.error("", e);
                }
                log.info("notify wait end");
                countDownLatch.countDown();
            }
        }).start();
        // notifyAll
        new Thread(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                log.error("", e);
            }
            synchronized (wait) {
                wait.notifyAll();
                log.info("notifyAll end");
            }
            countDownLatch.countDown();
        }).start();
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            log.error("", e);
        }
    }
}
